// page: window.root.novel.on_page
MAXPAGE = 57

function AttachClickEvents(){
	$("span.w").click(function(t){	// t: this
		options = {
			"apiUrl": "https://openapi.youdao.com/api",
			"appId": "31d827fff747577f",
			"secretKey": "OY9adlbEaiEmMquBQGStLeLN1up96uWJ",
			"from": "zh-CHS",
			"to": "en"
		}

		function Display(q,result){
			function GetHTML(q,result){
				if (parseInt(result.errorCode)) {
					return "请求错误，错误码：" + result.errorCode;
				}

				var content = '';
				if (result.basic !== undefined) {
					var explains = result.basic.explains;
					var i;

					for (i = 0; i < explains.length; i++) {
						var line = explains[i].replace(/^(\w+\.)/g, '<span class="htrans-tip-preposition">$1</span>');
						content += (i + 1) + ". </span>" + line + "<br />";
					}
				} else if (result.translation !== undefined) {
					for (i = 0; i < result.translation.length; i++) {
						content += (i + 1) + ". " + result.translation[i] + "<br />";
					}
				} else {
					return "无翻译结果。";
				}

				var title = '<span class="htrans-tip-query-word">' + q + '</span> ';

				return title + '<div class="htrans-tip-content">' + content + '</div>';
			}
			var html = GetHTML(q,result);
			console.log(html);
			$("#trans-result").html(html);
		}

		var word = t.target.innerText
		console.log(word);
		var salt = (new Date).getTime();
		var sign = md5(options.appId + word + salt + options.secretKey);

		$.ajax({
			url: options.apiUrl,
			type: 'post',
			async: false,
			dataType: 'jsonp',
			data: {
				q: word,
				appKey: options.appId,
				salt: salt,
				from: options.from,
				to: options.to,
				sign: sign
			},
			success: function(data){
				Display(word,data)
			},
			fail:function(){
				alert("获取数据失败");
			}
		})
	})
}

function RenderCurrentPage(){
	var page = window.root.novel.on_page
	raw_text = $.ajax({
		url: "res/" + page.toString() + ".js",
		async: false
	}).responseText
	function SplitHTML(s){
		var isAlpha = function(ch){
			return /^[A-Z]$/i.test(ch);
		}
		var nowS = ""
		var finalHTML = ""
		for( var index in s ){
			var c = s[index]
			if( isAlpha(c) ){
				nowS += c
			}else{
				finalHTML += "<span class=\"w\">" + nowS + "</span>" + c;
				if( c == '\n' ) finalHTML += "<br />"
				nowS = ""
			}
		}
		return finalHTML
	}
	$("#novel-content").html(SplitHTML(raw_text))

	$('.ui.sticky').sticky({
		content: '#novel-content'
	});
	$('#page_current').text(page.toString())
	AttachClickEvents()
}

function FlipPage(delta){
	var curPage = window.root.novel.on_page
	var newPage = curPage + delta
	if( newPage < 1 || newPage > MAXPAGE ) return
	window.root.novel.on_page = newPage
	SaveRootData()
	RenderCurrentPage()
}

function InitNovel(){
	RenderCurrentPage()
	$("#page_left").click(function(){
		FlipPage(-1)
	})
	$("#page_right").click(function(){
		FlipPage(+1)
	})
}
